package com.kasinf.springcloud.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.kasinf.springcloud.entity.CommonResult;
import com.kasinf.springcloud.entity.Payment;
import com.kasinf.springcloud.service.PaymentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;

/**
 * @author lkhsh
 */
@RestController
@Slf4j
public class CircleBreakerController {

    @Value("${nacos-user-service}")
    private String userService;

    @Resource
    private RestTemplate restTemplate;

    @GetMapping("consumer/fallback/{id}")
//    @SentinelResource(value = "fallback")
//    @SentinelResource(value = "fallback", fallback = "handlerFallback") // fallback 只负责业务异常
    @SentinelResource(value = "fallback", blockHandler = "blockHandler") // blockHandler 只负责控制台配置的违规
    public CommonResult<Payment> fallback(@PathVariable("id") Long id) {
        CommonResult<Payment> result = restTemplate.getForObject(userService + "/paymentSQL/" + id, CommonResult.class);
        if (id == 4) {
            throw new IllegalArgumentException("IllegalArgumentException,非法参数！！！！");
        } else if (null == result.getData()) {
            throw new NullPointerException("NullPointerException,没有对应记录！！！！");
        }
        return result;
    }

    public CommonResult<Payment> blockHandler(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(445, "blockHandler-sentinel限流，exception内容：" + e.getMessage(), payment);
    }

    public CommonResult<Payment> handlerFallback(@PathVariable Long id, Throwable e) {
        Payment payment = new Payment(id, "null");
        return new CommonResult<>(444, "兜底异常handlerFallback，exception内容：" + e.getMessage(), payment);
    }

    @Resource
    private PaymentService paymentService;

    @GetMapping("consumer/paymentSQL/{id}")
    public CommonResult<Payment> paymentSQL(@PathVariable("id") Long id){
        return paymentService.paymentSQL(id);
    }
}
